/*
This file is part of project qttraylauncher.

Copyright (c) 2014, Achim Köhler
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list
   of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, this
   list of conditions and the following disclaimer in the documentation and/or other
   materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/

#include "traylauncher.h"
#include "ddpushbutton.h"
#include "ddlabel.h"
#include "winhelper.h"


using namespace std;

Dialog::Dialog(QWidget *parent)
    : QDialog(parent)
{
    setWindowTitle(PROGNAME);
    setMinimumSize(400, 0);
    setWindowFlags(Qt::Dialog);

    QIcon icon = QIcon(":appicon.png");
    setWindowIcon(icon);

    minimizeAction = new QAction(tr("Mi&nimize"), this);
    connect(minimizeAction, SIGNAL(triggered()), this, SLOT(hide()));
    maximizeAction = new QAction(tr("Ma&ximize"), this);
    connect(maximizeAction, SIGNAL(triggered()), this, SLOT(showMaximized()));
    restoreAction = new QAction(tr("&Restore"), this);
    connect(restoreAction, SIGNAL(triggered()), this, SLOT(showNormal()));
    aboutAction = new QAction("About me", this);
    connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutMe()));
    aboutQtAction = new QAction("About Qt", this);
    connect(aboutQtAction, SIGNAL(triggered()), this, SLOT(aboutQt()));
    clearAction = new QAction("&Clear Settings", this);
    connect(clearAction, SIGNAL(triggered()), this, SLOT(clearSettings()));

    trayIconMenu = new QMenu(this);
    trayIconMenu->addAction(minimizeAction);
    trayIconMenu->addAction(maximizeAction);
    trayIconMenu->addAction(restoreAction);
    trayIconMenu->addSeparator();
    trayIconMenu->addAction(clearAction);
    trayIconMenu->addAction(aboutAction);
    trayIconMenu->addAction(aboutQtAction);
    trayIconMenu->addSeparator();
    trayIconMenu->addAction("&Quit",  qApp, SLOT(quit()));

    trayIcon.setIcon(icon);
    trayIcon.setToolTip("Launcher");
    trayIcon.setContextMenu(trayIconMenu);
    connect(&trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
    trayIcon.show();

    initPanel();
}

Dialog::~Dialog()
{

}

void Dialog::initPanel()
{
    int sizex, sizey, posx, posy;
    QString configFile;
    QStringList args = qApp->arguments();
    if (args.length() == 2 && args.indexOf("-n") == -1) {
        configFile = args.at(1);
    }
    else if (args.length() == 3) {
        configFile = args.at(2);
    }
    else {
        configFile = "config.json";
    }
    qDebug() << configFile << endl;
    QFile loadFile(configFile);
    if (!loadFile.open(QIODevice::ReadOnly)) {
        QMessageBox::critical(this, "Couldn't open config file",
            QString("Couldn't open config file %1").arg(configFile));
    }
    QTabWidget *tabWidget = new QTabWidget(this);
    QByteArray saveData = loadFile.readAll();
    QJsonDocument *loadDoc = new QJsonDocument(QJsonDocument::fromJson(saveData));
    QJsonArray config = loadDoc->array();
    for (int i = 0; i < config.size(); i++) {
        QJsonObject configitem = config[i].toObject();
        QWidget *appWidget = new QWidget(this);
        QGridLayout *layout = new QGridLayout(this);
        QJsonArray buttonlist = configitem.value("buttons").toArray();
        for (int row = 0; row < buttonlist.size(); row++) {
            QJsonObject button = buttonlist[row].toObject();
            DDPushButton *pushButton = new DDPushButton("Run");
            pushButton->setObjectName(button.value("name").toString());
            connect(pushButton, SIGNAL(clicked()), this, SLOT(buttonClicked()));
            //
            QString *command;
            QJsonArray commands = button.value("commands").toArray();
            for (int jj = 0; jj < commands.size(); jj++) {
                sizex = -1;
                sizey = -1;
                posx = -1;
                posy = -1;
                if (commands[jj].isObject()) {
                    QJsonObject commanditem = commands[jj].toObject();
                    command = new QString(commanditem.value("command").toString());
                    if (commanditem.contains("size")) {
                        QJsonArray array = commanditem.value("size").toArray();
                        sizex = array[0].toInt();
                        sizey = array[1].toInt();
                    }
                    if (commanditem.contains("position")) {
                        QJsonArray array = commanditem.value("position").toArray();
                        posx = array[0].toInt();
                        posy = array[1].toInt();
                    }
                } else {
                    command = new QString(commands[jj].toString());
                }
                pushButton->setConfig(sizex, sizey, posx, posy, command);
            }
            if (button.contains("draggable") && button.value("draggable").toBool(false)) {
                pushButton->setDropable(true);
            }
            if (button.contains("history") && button.value("history").toBool(false)) {
                QComboBox *cbHistory = new QComboBox();
                pushButton->setHistory(cbHistory);
                layout->addWidget(cbHistory, row, 2);
            }
            layout->addWidget(pushButton, row, 0);
            DDLabel *label = new DDLabel(button.value("name").toString());
            label->setPushButton(pushButton);
            layout->addWidget(label, row, 1);
        }
        layout->setColumnStretch(2, 1);
        appWidget->setLayout(layout);
        tabWidget->addTab(appWidget, configitem.value("tabname").toString());
    }
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(tabWidget);
    setLayout(layout);
    readSettings();
}

void Dialog::buttonClicked()
{
    DDPushButton *sender = (DDPushButton *)this->sender();
    for (unsigned int n = 0; n < sender->configlist.size(); n++) {
        config* c = sender->configlist.at(n);
        qDebug() << QString("cmd %1 pos(%2,%3) size(%4,%5)").arg(*(c->command)).arg(c->posx).arg(c->posy).arg(c->sizex).arg(c->sizey);
        QProcess *process = new QProcess(this);
        if (sender->data.size() <= 0) {
            if ((sender->cbHistory != NULL) && (sender->cbHistory->count() > 0)) {
                int index = sender->cbHistory->currentIndex();
                process->start(*(c->command), QStringList() << sender->cbHistory->itemText(index));
            } else {
                process->start(*(c->command));
            }
        } else {
            process->start(*(c->command), QStringList() << sender->data.at(0).toLocalFile());
        }
        if (((c->posx >= 0) && (c->posy >= 0)) || ((c->sizex >= 0) && (c->sizey >= 0))) {
            Q_PID pid = process->pid();
            std::vector<HWND> vecWindows;
            GetWindowsOfProcess(pid->dwProcessId, vecWindows);
            if (vecWindows.size() <= 0)
                continue;
            RECT r;
            GetWindowRect(vecWindows.at(0), &r);
            if ((c->posx >= 0) && (c->posy >= 0)) {
                r.left = c->posx;
                r.top = c->posy;
            }
            if ((c->sizex >= 0) && (c->sizey >= 0)) {
                r.right = r.left + c->sizex;
                r.bottom = r.top + c->sizey;
            }
            bool success = SetWindowPos(vecWindows.at(0), (HWND)0, r.left, r.top, r.right - r.left, r.bottom - r.top, 0);
            qDebug() << "SetWindowPos()" << success;
        }
    }


}

void Dialog::closeEvent(QCloseEvent *event)
{
    writeSettings();
    if (trayIcon.isVisible()) {
        this->hide();
    }
    if (qApp->arguments().indexOf("-n") != -1) {
        event->accept();
    } else {
        event->ignore();
    }
}

void Dialog::iconActivated(QSystemTrayIcon::ActivationReason reason)
{
    if (reason == QSystemTrayIcon::Trigger || reason == QSystemTrayIcon::DoubleClick) {
        this->setVisible(!this->isVisible());
        if (this->isVisible()) {
            this->showNormal();
        }
    } else if (reason == QSystemTrayIcon::MiddleClick) {
        /* do nothing */
    }
}

void Dialog::setVisible(bool visible)
{
    minimizeAction->setEnabled(visible);
    maximizeAction->setEnabled(!isMaximized());
    restoreAction->setEnabled(isMaximized() || !visible);
    QDialog::setVisible(visible);
}

void Dialog::aboutMe()
{
    QMessageBox::about(this, "About traylauncher",
        "<b>traylauncher</b><br/><br/>" \
        "Program to lauch configurable programs with optional arguments via " \
        "drag and drop or from history.<br/>" \
        "Configure via the file config.json<br/><br/>" \
        "(C) 2014 Achim Köhler");
}

void Dialog::aboutQt()
{
    QMessageBox::aboutQt(this);
}

void Dialog::clearSettings()
{
    QSettings settings;
    QStringList allKeys = settings.allKeys();
    for (int i = 0; i < allKeys.size(); i++) {
        settings.remove(allKeys.at(i));
    }
    QList<QComboBox *>comboBoxes = this->findChildren<QComboBox *>(QString());
    for (int i = 0; i < comboBoxes.size(); i++) {
        comboBoxes.at(i)->clear();
    }
}

void Dialog::writeSettings()
{
    QSettings settings;
    QTabWidget *tabWidget = this->findChildren<QTabWidget *>().at(0);
    QList<QWidget *> widgetsPages = this->findChildren<QWidget *>(QString(), Qt::FindDirectChildrenOnly);
    for (int i = 0; i < tabWidget->count(); i++) {
        settings.beginGroup(tabWidget->tabText(i));
        QList<DDPushButton *>pushButtons = tabWidget->widget(i)->findChildren<DDPushButton *>(QString(), Qt::FindDirectChildrenOnly);
        for (int j = 0; j < pushButtons.size(); j++) {
            if (pushButtons.at(j)->cbHistory == NULL) {
                continue;
            }
            settings.beginWriteArray("files");
            for (int k = 0; k < pushButtons.at(j)->cbHistory->count(); k++) {
                settings.setArrayIndex(k);
                settings.setValue(pushButtons.at(j)->objectName(), pushButtons.at(j)->cbHistory->itemText(k));
            }
            settings.endArray();
        }
        settings.endGroup();
    }
    settings.beginGroup("MainWindow");
    settings.setValue("size", size());
    settings.setValue("pos", pos());
    settings.endGroup();
}

void Dialog::readSettings()
{
    QSettings settings;
    QTabWidget *tabWidget = this->findChildren<QTabWidget *>().at(0);
    QList<QWidget *> widgetsPages = this->findChildren<QWidget *>(QString(), Qt::FindDirectChildrenOnly);
    for (int i = 0; i < tabWidget->count(); i++) {
        settings.beginGroup(tabWidget->tabText(i));
        QList<DDPushButton *>pushButtons = tabWidget->widget(i)->findChildren<DDPushButton *>(QString(), Qt::FindDirectChildrenOnly);
        for (int j = 0; j < pushButtons.size(); j++) {
            if (pushButtons.at(j)->cbHistory == NULL) {
                continue;
            }
            int size = settings.beginReadArray("files");
            for (int k = 0; k < size; k++) {
                settings.setArrayIndex(k);
                if (settings.contains(pushButtons.at(j)->objectName())) {
                    pushButtons.at(j)->cbHistory->addItem(settings.value(pushButtons.at(j)->objectName()).toString());
                }
            }
            settings.endArray();
        }
        settings.endGroup();
    }
    settings.beginGroup("MainWindow");
    resize(settings.value("size", minimumSize()).toSize());
    move(settings.value("pos", QPoint(200, 200)).toPoint());
    settings.endGroup();
}
